package com.bw.lib_net

import com.blankj.utilcode.util.SPUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import java.util.concurrent.TimeUnit

class RetrofitFactory private constructor() {
    private var retrofot: Retrofit

    init {
        retrofot = Retrofit.Builder()
            .client(getOkHttp())
            .baseUrl(BuildConfig.SERVER_HOST)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    private fun getOkHttp(): OkHttpClient {
        return OkHttpClient.Builder()
            .readTimeout(8, TimeUnit.SECONDS)
            .writeTimeout(8, TimeUnit.SECONDS)
            .connectTimeout(8, TimeUnit.SECONDS)
            .addInterceptor(createLog())
            .addInterceptor(Interceptor {
                val token = SPUtils.getInstance().getString("token", "")
                val request = it.request().newBuilder().addHeader("token", token).build()
                it.proceed(request)
            })
            .build()
    }

    private fun createLog(): Interceptor {
        return HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
    }

    companion object {
        private val intance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { RetrofitFactory() }
        fun getRetrofit(): RetrofitFactory {
            return intance
        }
    }

    fun <T> create(clazz: Class<*>): T {
        return retrofot.create(clazz) as T
    }
}








